package com.develop.GatewayService.FileSyncClient;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.develop.BeanUtils.Message;
import com.develop.BeanUtils.MsgType;
import com.develop.BeanUtils.SharedStorage;
import com.develop.vo.AlarmMsgVo;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.EventLoop;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.ReferenceCountUtil;

/**
 * 文件同步方式客户端 handler
 **/

public class FileSyncServiceHandler extends SimpleChannelInboundHandler<AlarmMsgVo> {
	private static final Logger LOG = LoggerFactory.getLogger(FileSyncServiceHandler.class);
	private AtomicInteger reqId;
	private FileSyncClient fileSyncClient;
	private String user;
	private String password;

	public FileSyncServiceHandler(String host, int port, String user, String password, AlarmMsgVo alarmMsgVo) {
		this.reqId = new AtomicInteger(0);
		this.user = user;
		this.password = password;
		this.fileSyncClient = new FileSyncClient(host, port, user, password, alarmMsgVo);
	}

	@Override
	protected void channelRead0(ChannelHandlerContext ctx, AlarmMsgVo alarmMsgVo) throws Exception {
		LOG.info("文件同步方式:接收到OMC消息:::" + alarmMsgVo.toString());
		try {
			if (alarmMsgVo.getMsgType() == MsgType.ackLoginAlarm.getIndex()) {
				if (alarmMsgVo.getBody().indexOf(";result=succ;") > 0) {
					LOG.info("文件同步方式:登录OMC失败,原因:{}", alarmMsgVo.getBody());
				}
			} else if (alarmMsgVo.getMsgType() == MsgType.ackSyncAlarmMsg.getIndex()) {
				// 消息同步告警请求的响应消息
				if (alarmMsgVo.getBody().contains("result=fail")) {
					// 失败：通知 【业务处理应用】
				}
			} else if (alarmMsgVo.getMsgType() == MsgType.ackSyncAlarmFile.getIndex()) {
				// 文件方式同步告警请求的响应消息
				if (alarmMsgVo.getBody().contains("result=fail")) {
					// 失败：通知 【业务处理应用】
				}
			} else if (alarmMsgVo.getMsgType() == MsgType.ackSyncAlarmFileResult.getIndex()) {
				// ackSyncAlarmFileResult;reqId=33;result=succ;filename=/ftproot/GD/MOBILE/HUAWEI/JS_OMC2/ALARM/20150611/GD-ALARM-OMC-1A-V1.1.0-20150611011603-ESB01-33-001.TXT.ZIP;resDesc=null
				// 文件方式同步告警请求的响应消息(含有文件同步结果的应答)
				// 成功：通知 【业务处理应用】

				SharedStorage.getBusinessGatewayClientChannel().writeAndFlush(alarmMsgVo);

				alarmMsgVo = Message.generateMessage((byte) MsgType.closeConnAlarm.getIndex(), MsgType.closeConnAlarm + "");
				ctx.channel().writeAndFlush(alarmMsgVo);
				LOG.info("文件同步方式:关闭OMC通道...");
			}
		} finally {
			ReferenceCountUtil.release(alarmMsgVo);
		}
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		LOG.info("文件同步方式:OMC通道已连接！");
		StringBuffer msgBodyBuffer = new StringBuffer();
		msgBodyBuffer.append(MsgType.reqLoginAlarm + ";");
		msgBodyBuffer.append("user=" + user + ";");
		msgBodyBuffer.append("key=" + password + ";");
		msgBodyBuffer.append("type=ftp");

		AlarmMsgVo alarmMsgVo = Message.generateMessage((byte) MsgType.reqLoginAlarm.getIndex(), msgBodyBuffer.toString());
		ctx.channel().writeAndFlush(alarmMsgVo);
		LOG.info("文件同步方式:请求登录OMC...");
	}

	/**
	 * 报错 处理事件
	 */
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		LOG.error("文件同步方式:客户端连接  Netty 出错..." + cause.getMessage());
		cause.printStackTrace();
	}

	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		// 使用过程中断线重连
		LOG.info("文件同步方式:OMC断线了...");
		final EventLoop eventLoop = ctx.channel().eventLoop();
		eventLoop.schedule(() -> fileSyncClient.run(), 1, TimeUnit.SECONDS);
		ctx.fireChannelInactive();
	}

	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
		/** 发送心跳,保持长连接 */
		StringBuffer msgBodyBuffer = new StringBuffer();
		msgBodyBuffer.append(MsgType.reqHeartBeat + ";");
		msgBodyBuffer.append("reqId=" + this.reqId.getAndIncrement());

		AlarmMsgVo alarmMsgVo = Message.generateMessage((byte) MsgType.reqHeartBeat.getIndex(), msgBodyBuffer.toString());
		ctx.channel().writeAndFlush(alarmMsgVo);
		LOG.info("文件同步方式:向OMC发送心跳...");
		super.userEventTriggered(ctx, evt);
	}
}
